#!/bin/bash

# DW SQL脚本管理工具开发环境设置脚本

set -e

echo "🚀 Setting up DW SQL Script Manager development environment..."

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

# 创建环境变量文件
if [ ! -f .env ]; then
    echo "📝 Creating .env file from template..."
    cp .env.example .env
    echo "✅ .env file created. Please review and update the configuration."
fi

# 启动数据库服务
echo "🐳 Starting database services with Docker Compose..."
docker-compose -f docker-compose.dev.yml up -d

# 等待数据库启动
echo "⏳ Waiting for databases to be ready..."
sleep 10

# 检查数据库健康状态
echo "🏥 Checking database health..."
max_attempts=30
attempt=1

while [ $attempt -le $max_attempts ]; do
    if docker-compose -f docker-compose.dev.yml exec -T postgres pg_isready -U postgres -d dw_sql_manager > /dev/null 2>&1; then
        echo "✅ PostgreSQL is ready"
        break
    fi
    
    if [ $attempt -eq $max_attempts ]; then
        echo "❌ PostgreSQL failed to start after $max_attempts attempts"
        exit 1
    fi
    
    echo "⏳ Waiting for PostgreSQL... (attempt $attempt/$max_attempts)"
    sleep 2
    ((attempt++))
done

# 检查Redis
if docker-compose -f docker-compose.dev.yml exec -T redis redis-cli ping > /dev/null 2>&1; then
    echo "✅ Redis is ready"
else
    echo "❌ Redis is not responding"
    exit 1
fi

# 安装后端依赖
if [ -d "backend" ]; then
    echo "📦 Installing backend dependencies..."
    cd backend
    npm install
    cd ..
fi

# 安装前端依赖
if [ -d "frontend" ]; then
    echo "📦 Installing frontend dependencies..."
    cd frontend
    npm install
    cd ..
fi

echo "🎉 Development environment setup completed!"
echo ""
echo "📋 Next steps:"
echo "  1. Review and update .env file if needed"
echo "  2. Run 'npm run test:db' in backend directory to test database connections"
echo "  3. Run 'npm run dev' in backend directory to start the backend server"
echo "  4. Run 'npm run dev' in frontend directory to start the frontend server"
echo ""
echo "🔗 Useful URLs:"
echo "  - pgAdmin: http://localhost:8080 (admin@example.com / admin123)"
echo "  - Redis Commander: http://localhost:8081"
echo "  - Backend API: http://localhost:3000"
echo "  - Frontend: http://localhost:5173"